package com.example.book_libapp;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.util.Log;

public class DownloadService extends AsyncTask<Void, Void, Boolean> {
	private final String TAG = "AsyncFileLoader";
	private String _urlStr;
	private URL _url;
	private URLConnection _urlConnection;
	private final int TIMEOUT_READ = 5000;
	private final int TIMEOUT_CONNECT = 30000;
	private InputStream _inputStream;
	private BufferedInputStream _bufferedInputStream;
	private FileOutputStream _fileOutputStream;
	private File _outputFile;
	private byte[] buff = new byte[5 * 1024];

	private int _totalByte = 0;
	private int _currentByte = 0;

	public DownloadService(String urlStr, File outputFile) {
		this._urlStr = urlStr;
		this._outputFile = outputFile;
	}

	@Override
	protected Boolean doInBackground(Void... params) {

		if (isCancelled()) {
			return false;
		}

		try {
			int len;
			while ((len = _bufferedInputStream.read(buff)) != -1) {
				_fileOutputStream.write(buff, 0, len);
				_currentByte += len;
				// publishProgress();
				if (isCancelled()) {
					break;
				}
			}

		} catch (IOException e) {
			Log.d(TAG, "error on read file:" + e.toString());
			return false;
		}
		return true;
	}

	@Override
	protected void onPreExecute() {
		try {
			connect();
		} catch (IOException e) {
			Log.d(TAG, "error on preExecute:" + e.toString());
			cancel(true);
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		if (result == true) {
			try {
				close();
			} catch (IOException e) {
				Log.d(TAG, "error on postExecute:" + e.toString());
			}
		} else {
			Log.d(TAG, "result: load error");
		}
	}

	private void connect() throws IOException {
		_url = new URL(_urlStr);
		_urlConnection = _url.openConnection();
		_urlConnection.setReadTimeout(TIMEOUT_READ);
		_urlConnection.setConnectTimeout(TIMEOUT_CONNECT);
		_inputStream = _urlConnection.getInputStream();
		_bufferedInputStream = new BufferedInputStream(_inputStream, 1024 * 5);
		_fileOutputStream = new FileOutputStream(_outputFile);

		// _totalByte = _bufferedInputStream.available(); //this is not work
		_totalByte = _urlConnection.getContentLength();
		_currentByte = 0;
	}

	private void close() throws IOException {
		_fileOutputStream.flush();
		_fileOutputStream.close();
		_bufferedInputStream.close();
	}

	public int getLoadedBytePercent() {
		if (_totalByte <= 0) {
			return 0;
		}
		// Log.d(TAG, Integer.toString(_currentByte) + ":" +
		// Integer.toString(_totalByte));
		return (int) Math.floor(100 * _currentByte / _totalByte);
	}
}